﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CPPEI.Coolzon.UI.Data
{
    public class ExtentionFunctionLoader
    {
        private static ExtentionFunctionLoader s_instance;
        private static object s_lockObj = new object();

        public static ExtentionFunctionLoader Instance
        {
            get
            {
                if (s_instance == null)
                {
                    lock (s_lockObj)
                    {
                        if (s_instance == null)
                        {
                            s_instance = new ExtentionFunctionLoader();
                        }
                    }
                }
                return s_instance;
            }
        }

        public List<ExtentionFunction> FunctionList { get; private set; }

        /// <summary>
        /// 加载扩展方法
        /// </summary>
        /// <param name="extentionFuctionConfigFilePath"></param>
        /// <returns></returns>
        public List<ExtentionFunction> Load(string extentionFuctionConfigFilePath)
        {
            if (FunctionList == null)
            {
                FunctionList = new List<ExtentionFunction>();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(extentionFuctionConfigFilePath);
                XmlNodeList xmlFunctions = xmlDoc.SelectNodes("./ExtentionFunction/Function");
                foreach (XmlNode xmlFunction in xmlFunctions)
                {
                    XmlAttribute xName = xmlFunction.Attributes["Name"];
                    XmlAttribute xCaption = xmlFunction.Attributes["Caption"];
                    XmlAttribute xMode = xmlFunction.Attributes["Mode"];
                    XmlNode xAction = xmlFunction.SelectSingleNode("./Action");
                    XmlNode xArguments = xmlFunction.SelectSingleNode("./Arguments");
                    XmlNode xFilter = xmlFunction.SelectSingleNode("./Filter");

                    ExtentionFunction function = new ExtentionFunction();
                    function.Name = xName.Value;
                    function.Caption = xCaption.Value;
                    function.Mode = xMode.Value;
                    function.Action = xAction.InnerText.Trim();
                    function.Arguments = xArguments.InnerText.Trim();
                    if (xFilter != null)
                    {
                        function.Filter = xFilter.InnerText.Trim();
                    }

                    FunctionList.Add(function);
                }
            }

            return FunctionList;
        }

    }
}
